//ajax请求
(function (w) {
    var time;
    var netWork = function (data,method) {
            if(data.loading) data.loading();//显示加载中
            if(data.native == false){//zepto请求
                $.ajax({
                    url: data.url,
                    type: data.method?data.method:"get",
                    dataType: "json",
                    data: data.data,
                    timeout: data.prize?8000:40000,
                    success: function (d) {
                        if(data.endLoading) data.endLoading();//结束加载中
                        if(method) method(d);
                    },
                    error: function (res,e) {
                        console.log(e+": "+JSON.stringify(res));
                        if (e == "timeout") {
                            tip.toast("网络比较差，请稍后再试");
                        }
                        else if (e == "abort") {
                            tip.toast("网络有问题，请稍后再试");
                        }
                        //else if (res.status == 200) {
                        //
                        //}
                        else {
                            tip.toast("网络不给力，请稍后再试");
                        }
                        cw.buttonAjax = true;
                        if(data.logger)data.logger(res,e);
                    }
                });
            }else{ //原生请求
                //jsonp跨域
                // var script = document.createElement('script');
                // script.type = "text/javascript";
                // script.src = data.url+"&callback="+method;
                // document.head.appendChild(script);
                // return;
                //正常请求
                try {
                    var xmlhttp;
                    if (window.XMLHttpRequest){
                        xmlhttp=new XMLHttpRequest();
                    }
                    else {
                        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    xmlhttp.onreadystatechange=function()
                    {
                        if (xmlhttp.readyState==4 && xmlhttp.status==200)
                        {
                            if(data.endLoading) data.endLoading();//结束加载中
                            if(method) method(xmlhttp.responseText);
                        }
                    }

                    if(data.method && data.method == "post"){
                        xmlhttp.open("post",data.url,data.sync?false:true);
                        if(data.formData){
                            xmlhttp.send(data.formData);
                        }else{
                            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//普通表单类型，键值对
                            xmlhttp.send(data.data);
                        }
                    }else{
                        xmlhttp.open("get",data.url,data.sync?false:true);
                        xmlhttp.send();
                    }
                    time = setTimeout(function(){
                        if(data.prize && (xmlhttp.readyState!=4 || xmlhttp.status!=200)){//抽奖按钮控制
                            xmlhttp.abort();
                            if(data.endLoading) data.endLoading();//结束加载中
                            noNetwork();
                            if(data.thisObj)data.thisObj.buttonControl = false;
                        }
                    },6000);
                    //setTimeout(function(){
                    //    if(data.prize && !xmlhttp.statusText){
                    //        if(document.getElementById("toast")){
                    //            xmlhttp.abort();
                    //            if(data.endLoading) data.endLoading();//结束加载中
                    //            document.getElementById("toast").innerText = "亲，请检查你的网络君～";//
                    //            document.getElementById("toast").className += " toasts";
                    //            clearTimeout(time);
                    //            if(data.thisObj)data.thisObj.buttonControl = false;
                    //            return false;
                    //        }
                    //    }
                    //},800);
                } catch(e) {
                    console.log(e.name +" "+ e.message);
                } finally {

                }
            }
        },
    //获取参数key值
        getQueryString = function(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = decodeURI(window.location.search).substr(1).match(reg);
            if (r != null) return unescape(r[2]); return "";
        },
    //无网络，自己调用
        noNetwork = function(){
            if(document.getElementById("toast")){
                document.getElementById("toast").innerText = "亲，请求超时～";//亲，请检查你的网络君～
                document.getElementById("toast").className += " toasts";
            }
        },
    //图片加载错误处理
        imgLoadError = function(obj){
            <!--  宝宝树66小区二次改造    mod   张秘  20170718   start-->
            obj.src = cw.resUrl+"images/com/portrait_normal.jpg";//默认头像
            <!--  宝宝树66小区二次改造    mod   张秘  20170718   end-->
        },
    //数字加0
        numTowDisplay = function(num){
            if(num < 10 && num >= 0){
                num = "0"+num;
            }
            return num;
        },
    //时间格式化
        formatTime = function(date){
            return numTowDisplay(date.getFullYear())+"-"+numTowDisplay(date.getMonth()+1)+"-"+numTowDisplay(date.getDate())+" "+ numTowDisplay(date.getHours())+":"+ numTowDisplay(date.getMinutes());
        },
    //公司时间规则
        formatTimeRule = function(date){
            var d = new Date(date),now = new Date(),
                dStamp = d.getTime(),nowStamp = now.getTime();
            if(now.getFullYear() - d.getFullYear() > 0){
                return numTowDisplay(d.getFullYear())+"-"+numTowDisplay(d.getMonth()+1)+"-"+numTowDisplay(d.getDate());
            }else if((nowStamp - dStamp)/1000 < 60){
                return "刚刚";
            }else if((nowStamp - dStamp)/60000 < 60){
                return Math.floor((nowStamp - dStamp)/60000)+"分钟前";
            }else if((nowStamp - dStamp)/3600000 < 24){
                return Math.floor((nowStamp - dStamp)/3600000)+"小时前";
            }else if((nowStamp - dStamp)/86400000 >= 1 && (nowStamp - dStamp)/86400000 <= 3){
                return Math.floor((nowStamp - dStamp)/86400000)+"天前";
            }else if((nowStamp - dStamp)/86400000 > 3){
                return numTowDisplay(d.getMonth()+1)+"月"+numTowDisplay(d.getDate())+"日";
            }
        },
    //去掉空格
        trim = function(str){
            return str.replace(/\s/g, "");
        };

    w.getQueryString = getQueryString;
    w.netWork = netWork;//ajax
    w.imgLoadError = imgLoadError;
    w.numTowDisplay = numTowDisplay;
    w.formatTime = formatTime;
    w.formatTimeRule = formatTimeRule;
    w.trim = trim;
    //控制器对象
    w.cw = {
        buttonAjax: true,
        resUrl: "",//http://66xiaoqu.babytreeimg.com/app/
        htmlUrl: "",//http://d.h5.66xiaoqu.com/app/
        serverUrl: ""//http://app.66xiaoqu.com
    };

})(window);


//检测网络
window.addEventListener("offline" , function()
{
    //if(document.getElementById("toast")){
    //    document.getElementById("toast").innerText = "亲，请检查你的网络君～";
    //    document.getElementById("toast").className += " toasts";
    //}
    tip.toast("亲，请检查你的网络君～");
} , true);



//function trim(str){  //删除左右两端的空格
//    return str.replace(/(^\s*)|(\s*$)/g, "");
//}
//function ltrim(str){  //删除左边的空格
//    return str.replace(/(^\s*)/g,"");
//}
//function rtrim(str){  //删除右边的空格
//    return str.replace(/(\s*$)/g,"");
//}

